<template>
  <div class="content">
    <el-card>
      <div class="nav-wrap">
        <div class="title">券码管理</div>
      </div>
      <!-- <div class="operate-wrap">
        <el-button type="primary" icon="el-icon-plus" @click="openDialog" size="mini">新增</el-button>
      </div> -->
      <div class="query-form">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="券码" size="mini">
            <el-input v-model="queryForm.code" placeholder="请输入券码" size="mini" />
          </el-form-item>
          <el-form-item label="状态" size="mini">
            <el-select v-model="queryForm.orderStatus" placeholder="请选择状态" size="mini">
              <el-option v-for="item in statusList" :key="item.key" :label="item.name" :value="item.key"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item size="mini">
            <el-button type="primary" @click="onQuery" size="mini">查询</el-button>
            <el-button @click="onReset" size="mini">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="operate-wrap">
        <el-button type="primary" icon="el-icon-download" @click="exportExcel" size="mini">导出Excel</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="multiDelete" size="mini">批量删除</el-button>
        <el-button type="success" icon="el-icon-copy-document" @click="multiRemark" size="mini">批量备注</el-button>
        <div class="query-form myForm">
          <el-form :inline="true" :model="addForm" class="demo-form-inline">
            <el-form-item label="券码数量：">
              <el-input-number v-model="addForm.num" :min="1" :max="200" label="请输入随机券码数量" size="small"></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="generateRandomCoupon" size="small">生成</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="table-wrap">
        <el-table :data="tableData" style="width: 100%" header-row-class-name="table-header" @selection-change="handleSelectionChange">
          <!-- <el-table-column prop="id" label="ID" width="100"></el-table-column> -->
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="code" label="券码"></el-table-column>
          <el-table-column prop="password" label="密码" width="120"></el-table-column>
          <el-table-column prop="couponStatusName" label="兑换状态" width="100"></el-table-column>
          <el-table-column prop="couponRemark" label="备注"></el-table-column>
          <!-- <el-table-column prop="exchangeTime" label="兑换时间"></el-table-column> -->
          <el-table-column label="操作">
            <template slot-scope="scope">
              <div style="display: flex; flex-wrap: wrap; gap: 10px">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="openDialog(scope.row, 'coupon')"
                  :disabled="parseInt(scope.row.couponStatus, 10) !== 0"
                  style="margin-left: 0px"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  :disabled="parseInt(scope.row.couponStatus, 10) !== 0"
                  style="margin-left: 0px"
                  >删除</el-button
                >
                <el-button
                  type="primary"
                  @click="openDialog(scope.row, 'remark')"
                  size="mini"
                  icon="el-icon-copy-document"
                  style="margin-left: 0px"
                  >备注</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-wrap">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryForm.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryForm.showCount"
          :layout="paginationLayoutStr"
          :total="total"
        >
        </el-pagination>
      </div>
      <el-dialog :title="dialogTitle" width="400px" :visible.sync="dialogVisible">
        <el-form ref="dialogForm" :model="dialogForm" label-width="120px" class="dialogForm" :rules="dialogFormRules">
          <el-form-item label="券码" prop="code" v-if="dialogType.indexOf('Coupon') > -1">
            <el-input v-model="dialogForm.code" placeholder="请输入券码" maxlength="20" />
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="dialogType.indexOf('Coupon') > -1">
            <el-input v-model="dialogForm.password" placeholder="请输入密码" maxlength="10" />
          </el-form-item>
          <el-form-item prop="remark" v-if="dialogType.indexOf('Remark') > -1">
            <el-input type="textarea" autosize placeholder="请输入备注" v-model="dialogForm.remark"> </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="confirmEdit">确 定</el-button>
          <el-button @click="cancelEdit">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog title="批量备注" width="400px" :visible.sync="multiRemarkDialogVisible">
        <el-form ref="dialogForm" :model="dialogForm" label-width="120px" class="dialogForm">
          <el-form-item prop="remark">
            <el-input type="textarea" autosize placeholder="请输入备注" v-model="multiRemarkCt"> </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="confirmMultiRemark">确 定</el-button>
          <el-button @click="cancelMultiRemark">取 消</el-button>
        </div>
      </el-dialog>
    </el-card>
    <el-card style="margin-top: 40px">
      <div class="nav-wrap">
        <div class="title">可兑换时间管理</div>
      </div>
      <div class="query-form">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="兑换时间">
            <el-date-picker
              v-model="operateTimeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="mini"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="editTimeRange" size="mini">修改</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  listCoupons,
  addCoupon,
  updateCoupon,
  queryTimeConfig,
  updateTimeConfig,
  exportCoupon,
  deleteCoupon,
  generateCoupon,
  batchDeleteCoupon,
  updateCouponRemark,
} from '@/api/index';

export default {
  name: 'coupon',
  data() {
    return {
      tableData: [
        {
          id: '',
          code: '', // 券码
          password: '', // 密码
          // exchangeTime: '', // 可兑换时间
        },
      ],
      statusList: [
        {
          key: '0',
          name: '未兑换',
        },
        {
          key: '1',
          name: '已兑换',
        },
        // {
        //   key: '2',
        //   name: '已发货',
        // },
        // {
        //   key: '3',
        //   name: '已签收',
        // },
      ],
      queryForm: {
        // exchangeTime: '',
        code: '', // 券码
        orderStatus: '', // 兑换状态
        currentPage: 1,
        showCount: 10,
      },
      total: 1,
      // searchTimeRange: [],
      operateTimeRange: [],
      exchangeTime: '',
      configId: '',
      dialogForm: {
        code: '',
        password: '',
        remark: '',
      },
      editId: '',
      editCouponId: '',
      dialogFormRules: {
        code: [{ required: true, trigger: 'blur', message: '券码不能为空' }],
        password: [{ required: true, trigger: 'blur', message: '密码不能为空' }],
      },
      dialogVisible: false,
      dialogType: 'addCoupon', // 取值 addCoupon editCoupon addRemark editRemark
      paginationLayoutStr: 'total, sizes, prev, pager, next, jumper',
      addForm: {
        // 生成券码和密码的个数
        num: 0,
      },
      multiDeleteIds: [],
      multiRemarkCt: '',
      multiRemarkDialogVisible: false,
    };
  },
  created() {
    this.getList();
    this.getTimeConfig();
    if (this.$store.state.screenWidth < 990) {
      this.paginationLayoutStr = 'total, prev, next';
    }
  },
  computed: {
    dialogTitle() {
      let tmpTitle;
      if (this.dialogType === 'addCoupon') {
        tmpTitle = '新增券码';
      } else if (this.dialogType === 'editCoupon') {
        tmpTitle = '编辑券码';
      } else if (this.dialogType === 'addRemark') {
        tmpTitle = '添加备注';
      } else if (this.dialogType === 'editRemark') {
        tmpTitle = '修改备注';
      }
      return tmpTitle;
    },
    exportBtnVisile() {
      return this.tableData.length > 0;
    },
  },
  methods: {
    onQuery() {
      console.log(this.queryForm);
      this.getList();
    },
    onReset() {
      this.queryForm = {
        code: '',
        orderStatus: '',
        currentPage: 1,
        showCount: 10,
      };
      this.getList();
    },
    covertTimeRange(dateRageArr) {
      const startTime = dateRageArr[0];
      const endTime = dateRageArr[1];
      const startMonth = startTime.getMonth() + 1 < 10 ? `0${startTime.getMonth() + 1}` : startTime.getMonth() + 1;
      const startDay = startTime.getDate() < 10 ? `0${startTime.getDate()}` : startTime.getDate();
      const endMonth = endTime.getMonth() + 1 < 10 ? `0${endTime.getMonth() + 1}` : endTime.getMonth() + 1;
      const endDay = endTime.getDate() < 10 ? `0${endTime.getDate()}` : endTime.getDate();
      // 时分秒
      const startHour = startTime.getHours() < 10 ? `0${startTime.getHours()}` : startTime.getHours();
      const startMinute = startTime.getMinutes() < 10 ? `0${startTime.getMinutes()}` : startTime.getMinutes();
      const startSecond = startTime.getSeconds() < 10 ? `0${startTime.getSeconds()}` : startTime.getSeconds();
      const endHour = endTime.getHours() < 10 ? `0${endTime.getHours()}` : endTime.getHours();
      const endMinute = endTime.getMinutes() < 10 ? `0${endTime.getMinutes()}` : endTime.getMinutes();
      const endSecond = endTime.getSeconds() < 10 ? `0${endTime.getSeconds()}` : endTime.getSeconds();
      const tmpTimeRangeStr = `${startTime.getFullYear()}-${startMonth}-${startDay} ${startHour}:${startMinute}:${startSecond},${endTime.getFullYear()}-${endMonth}-${endDay} ${endHour}:${endMinute}:${endSecond}`;
      return tmpTimeRangeStr;
    },
    covertTimeRangeStr(dataRangeStr) {
      const tmpArr = dataRangeStr.split(',');
      const startTime = tmpArr[0];
      const endTime = tmpArr[1];
      const tmpTimeRangeArr = [new Date(startTime), new Date(endTime)];
      return tmpTimeRangeArr;
    },
    handleSizeChange(e) {
      this.queryForm.showCount = e;
      this.getList();
    },
    handleCurrentChange(e) {
      this.queryForm.currentPage = e;
      this.getList();
    },
    openDialog(e, serviceType) {
      // serviceType取值 coupon remark
      if (serviceType === 'coupon') {
        if (!e.id) {
          this.dialogType = 'addCoupon';
          this.dialogForm = {
            code: '',
            password: '',
          };
        } else {
          this.dialogType = 'editCoupon';
          console.log(e);
          this.editId = e.id;
          this.dialogForm = {
            code: e.code,
            password: e.password,
          };
        }
        this.dialogVisible = true;
      } else {
        // 添加/更新备注
        this.editCouponId = e.id;
        if (e.couponRemark) {
          this.dialogType = 'editRemark';
          this.dialogForm = {
            remark: e.couponRemark,
          };
        } else {
          this.dialogType = 'addRemark';
          this.dialogForm = {
            remark: '',
          };
        }
        this.dialogVisible = true;
      }
    },
    confirmEdit() {
      if (this.dialogType === 'addCoupon' || this.dialogType === 'editCoupon') {
        this.$refs.dialogForm.validate((valid) => {
          if (valid) {
            console.log(this.dialogForm);
            // code是20位的数字和字母(由数字和字母组成，长度为20位)
            // password是10位的数字
            const codeRegex = /^[0-9a-zA-Z]{20}$/;
            const passwordRegex = /^[0-9]{10}$/;
            if (!codeRegex.test(this.dialogForm.code.trim())) {
              this.$message.error('券码由数字和字母组成,长度为20位!');
              return;
            }
            if (!passwordRegex.test(this.dialogForm.password.trim())) {
              this.$message.error('密码由数字组成,长度为10位!');
              return;
            }
            if (this.dialogType === 'addCoupon') {
              addCoupon({
                couponCode: this.dialogForm.code.trim(),
                couponPwd: this.dialogForm.password.trim(),
              })
                .then((res) => {
                  console.log(res);
                  this.$message.success('新增成功');
                  this.dialogVisible = false;
                  this.getList();
                })
                .catch((err) => {
                  console.log(err);
                  this.dialogVisible = false;
                  this.$message.error('新增失败');
                });
            } else if (this.dialogType === 'editCoupon') {
              updateCoupon({
                couponId: this.editId,
                couponCode: this.dialogForm.code.trim(),
                couponPwd: this.dialogForm.password.trim(),
              })
                .then((res) => {
                  console.log(res);
                  this.dialogVisible = false;
                  this.$message.success('编辑成功');
                  this.getList();
                })
                .catch((err) => {
                  console.log(err);
                  this.dialogVisible = false;
                  this.$message.error('编辑失败');
                });
            }
          }
        });
      } else {
        // 添加/更新备注
        if (!this.dialogForm.remark) {
          this.$message({
            message: '请输入备注!',
            type: 'warning',
          });
          return;
        }
        console.log(this.dialogForm.remark);
        updateCouponRemark({
          couponId: this.editCouponId,
          couponRemark: this.dialogForm.remark,
        })
          .then((res) => {
            console.log(res);
            this.$message({
              message: `${this.dialogTitle}成功`,
              type: 'success',
            });
            this.dialogVisible = false;
            this.getList();
          })
          .catch((err) => {
            console.log(err);
            this.dialogVisible = false;
            this.$message({
              message: `${this.dialogTitle}失败`,
              type: 'error',
            });
          });
      }
    },
    cancelEdit() {
      this.dialogVisible = false;
      this.dialogType = '';
    },
    handleDelete(e) {
      // 询问是否删除券码为e.code的券码
      console.log(e);
      this.$confirm(`是否删除券码为${e.code}的券`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          console.log('确定删除');
          deleteCoupon({
            couponId: e.id,
          })
            .then((res) => {
              console.log(res);
              if (res.data.code === '000007') {
                this.$message.error(res.data.msg);
              } else {
                this.$message.success('删除成功!');
                this.getList();
              }
            })
            .catch((err) => {
              console.log(err);
              this.$message.error('删除失败!');
            });
        })
        .catch(() => {
          console.log('取消删除');
        });
    },
    getList() {
      listCoupons({
        couponCode: this.queryForm.code.trim(),
        couponStatus: this.queryForm.orderStatus,
        pageNum: this.queryForm.currentPage,
        pageSize: this.queryForm.showCount,
      })
        .then((res) => {
          console.log(res);
          this.tableData = res.data.resData.list.map((item) => {
            return {
              id: item.couponId,
              code: item.couponCode,
              password: item.couponPwd,
              couponStatus: item.couponStatus,
              couponStatusName: this.statusList.find((status) => parseInt(status.key, 10) === parseInt(item.couponStatus, 10))?.name ?? '',
              couponRemark: item.couponRemark,
            };
          });
          this.total = res.data.resData.total;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getTimeConfig() {
      queryTimeConfig()
        .then((res) => {
          console.log(res);
          this.configId = res.data.resData.configId;
          this.exchangeTime = `${res.data.resData.startTime},${res.data.resData.endTime}`;
          this.operateTimeRange = this.covertTimeRangeStr(this.exchangeTime);
          console.log(this.exchangeTime);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    editTimeRange() {
      this.exchangeTime = this.covertTimeRange(this.operateTimeRange);
      if (!this.exchangeTime) {
        this.$message.error('请选择兑换时间');
      }
      console.log(this.exchangeTime, this.operateTimeRange);
      updateTimeConfig({
        configId: this.configId,
        startTime: this.exchangeTime.split(',')[0],
        endTime: this.exchangeTime.split(',')[1],
      })
        .then((res) => {
          console.log(res);
          this.$message.success('修改成功!');
        })
        .catch((err) => {
          console.log(err);
          this.$message.error('修改失败!');
        });
    },
    generateRandomCoupon() {
      console.log(this.addForm);
      if (!this.addForm.num) {
        this.$message.error('请输入生成数量!');
        return;
      }
      generateCoupon({
        amount: this.addForm.num,
      })
        .then((res) => {
          console.log(res);
          this.$message.success('生成成功!');
          this.addForm.num = 0;
          this.getList();
        })
        .catch((err) => {
          console.log(err);
          this.$message.error('生成失败!');
        });
    },
    exportExcel() {
      if (!this.exportBtnVisile) {
        this.$message.error('没有可导出的数据!');
        return;
      }
      exportCoupon({
        couponCode: this.queryForm.code.trim(),
        couponStatus: this.queryForm.orderStatus,
      }).then((res) => {
        console.log(res);
        // 创建Blob对象
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
        // 创建URL
        const url = URL.createObjectURL(blob);
        // 创建a标签
        const a = document.createElement('a');
        a.href = url;
        a.download = '券码.xlsx'; // 指定下载文件名
        // 触发点击事件
        a.click();
      });
    },
    multiDelete() {
      if (this.multiDeleteIds.length === 0) {
        this.$message.error('请选择要删除的券码');
        return;
      }
      this.$confirm('是否删除选中的券码', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          console.log('确定删除');
          batchDeleteCoupon({
            couponIds: this.multiDeleteIds.join(','),
          })
            .then((res) => {
              console.log(res);
              if (res.data.code === '000000') {
                this.$message.success('删除成功!');
                this.getList();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((err) => {
              console.log(err);
              this.$message.error('删除失败!');
            });
        })
        .catch(() => {
          console.log('取消删除');
        });
    },
    handleSelectionChange(selection) {
      this.multiDeleteIds = selection.map((item) => item.id);
      console.log(this.multiDeleteIds);
    },
    multiRemark() {
      if (this.multiDeleteIds.length === 0) {
        this.$message.error('请选择要批量备注的券码');
        return;
      }
      this.multiRemarkDialogVisible = true;
    },
    requestMultiRemark() {
      const asyncTask = [];
      this.multiDeleteIds.forEach((id) => {
        asyncTask.push(
          updateCouponRemark({
            couponId: id,
            couponRemark: this.multiRemarkCt,
          }),
        );
      });
      Promise.all(asyncTask)
        .then((res) => {
          console.log(res);
          this.$message.success('批量备注成功!');
          this.multiRemarkDialogVisible = false;
          this.getList();
        })
        .catch((err) => {
          console.log(err);
          this.$message.error('批量备注失败!');
        });
    },
    confirmMultiRemark() {
      if (!this.multiRemarkCt) {
        this.$message.error('请输入批量备注的内容');
        return;
      }
      this.requestMultiRemark();
    },
    cancelMultiRemark() {
      this.multiRemarkCt = '';
      this.multiRemarkDialogVisible = false;
    },
  },
};
</script>
<style scoped lang="less">
.nav-wrap {
  display: flex;
  align-items: center;
  height: 40px;
  .title {
    padding-left: 18px;
    height: 26px;
    font-size: 19px;
    font-weight: 500;
    color: #3b3c3d;
    line-height: 26px;
    position: relative;
    top: -20px;
    left: -20px;
    &::after {
      content: '';
      position: absolute;
      left: 0;
      width: 6px;
      height: 100%;
      background: #1e87f0;
      border-radius: 3px;
    }
  }
}
.operate-wrap {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  .myForm::v-deep {
    margin-left: 20px;
    .el-form-item {
      margin-bottom: 0;
    }
  }
}
.table-wrap::v-deep {
  flex: 1;
  height: 100%;
  .table-header {
    th {
      color: rgba(0, 0, 0, 0.85);
      background-color: #fafafa;
    }
    .cell {
      font-size: 13px;
      color: rgba(0, 0, 0, 0.65);
    }
    .column-header {
      font-weight: bold;
    }
  }
  .padding-left {
    padding-left: 20px;
  }
}
.pagination-wrap {
  padding: 20px;
  display: flex;
  justify-content: flex-end;
}

@media screen and (max-width: 990px) {
  .query-form::v-deep {
    .el-date-editor--datetimerange.el-input__inner {
      width: 100%;
    }
    .el-date-editor .el-range-input {
      font-size: 8px;
    }
    .el-date-editor .el-range-separator {
      font-size: 8px;
    }
    .el-date-editor .el-range__icon {
      display: none;
    }
  }
}
</style>
